#include "main.h"
#include "uart.h"
#include <string.h>

#define WIFI	"\"Better_day\",\"yangche123\""
#define TCP		"\"TCP\",\"n87ieud.mqtt.iot.gz.baidubce.com\",1883"

static int esp8266_at_cmd(char *cmd, char *ack_need, int timeout)
{
	char at_cmd[100];
	char rcv_ack[RX_BUFF_LEN];
	uint16_t rcv_len;

	memset(at_cmd, 0, 100);
	memset(rcv_ack, 0, 512);

	strcpy(at_cmd, "AT");
	if (cmd != NULL) {
		strcat(at_cmd, cmd);
	}
	strcat(at_cmd, "\r\n");

	uart_recv((uint8_t*) rcv_ack, &rcv_len);
	uart_send((uint8_t*) at_cmd, strlen(at_cmd));
	while (timeout--) {
		HAL_Delay(100);
		if (uart_recv((uint8_t*) rcv_ack, &rcv_len) == 0) {
			if (ack_need == NULL) {
				HAL_Delay(1000);
				return 0;
			}
			if (strstr(rcv_ack, ack_need) != NULL) {
				return 0;
			}
		}
	}

	return -1;
}

static int esp8266_reset(void)
{
	uart_send((uint8_t*) "+++", strlen("+++"));
	HAL_Delay(100);
	if (esp8266_at_cmd("+RESTORE", NULL, 30) < 0) {
		return -1;
	}
	return 0;
}

static int esp8266_wifi_link()
{
	if (esp8266_at_cmd("+CWMODE=3", "OK", 30) < 0) {
		return -1;
	}
	if (esp8266_at_cmd("+CWJAP="WIFI, "OK", 100) < 0) {
		return -1;
	}
	return 0;
}

static int esp8266_tcp_link()
{
	if (esp8266_at_cmd("+CIFSR", "OK", 20) < 0) {
		return -1;
	}
	if (esp8266_at_cmd("+CIPSTART="TCP, "OK", 50) < 0) {
		return -1;
	}
	return 0;
}

static int esp8266_pass()
{
	if (esp8266_at_cmd("+CIPMODE=1", "OK", 20) < 0) {
		return -1;
	}
	if (esp8266_at_cmd("+CIPSEND", ">", 20) < 0) {
		return -1;
	}
	return 0;
}
int esp8266_init(void)
{
	if (esp8266_reset() < 0) {
		return -1;
	}
	if (esp8266_wifi_link() < 0) {
		return -1;
	}
	if (esp8266_tcp_link() < 0) {
		return -1;
	}
	if (esp8266_pass() < 0) {
		return -1;
	}
	return 0;
}

int esp8266_send(uint8_t *mqtt_cmd, uint16_t len)
{
	uint8_t tmp[RX_BUFF_LEN];
	uint16_t tmp_len;
	uart_recv(tmp, &tmp_len);
	uart_send(mqtt_cmd, len);
	return 0;
}

int esp8266_recv(uint8_t *mqtt_recv, uint16_t *len)
{
	return uart_recv(mqtt_recv, len);
}

